"""主备模型切换逻辑（QPS触发）"""
"""模型选择器（根据性能自动切换模型）"""
from typing import Dict, Any, Optional
from fin_senti_entity_platform.utils.logger import Logger
from fin_senti_entity_platform.utils.config_loader import ConfigLoader
from fin_senti_entity_platform.model_development.sentiment_analysis.base_sentiment_model import SentimentModelFactory
from fin_senti_entity_platform.service_deployment.degradation.performance_monitor import get_performance_monitor


class ModelSelector:
    """模型选择器类，用于根据系统状态选择合适的模型"""
    
    def __init__(self):
        """初始化模型选择器"""
        self.logger = Logger().get_logger(__name__)
        self.config = ConfigLoader().get_config('service', 'degradation')
        self.performance_monitor = get_performance_monitor()
        self.fallback_model_type = self.config.get('fallback_model', 'bert_base')
        self.models = {}
        self.current_model_type = 'deepseek'  # 默认使用高性能模型
    
    def register_model(self, model_type: str, model):
        """注册模型实例
        
        Args:
            model_type: 模型类型
            model: 模型实例
        """
        self.models[model_type] = model
        self.logger.info(f"已注册模型: {model_type}")
    
    def get_model(self, request_context: Optional[Dict[str, Any]] = None) -> Any:
        """获取适合当前请求的模型
        
        Args:
            request_context: 请求上下文信息
            
        Returns:
            Any: 选定的模型实例
        """
        # 检查是否需要降级
        degradation_status = self.performance_monitor.get_degradation_status()
        
        if degradation_status['is_degraded'] and self.fallback_model_type in self.models:
            # 使用回退模型
            if self.current_model_type != self.fallback_model_type:
                self.current_model_type = self.fallback_model_type
                self.logger.warning(f"由于性能原因，切换到回退模型: {self.fallback_model_type}")
            return self.models[self.fallback_model_type]
        else:
            # 使用默认模型
            if self.current_model_type != 'deepseek' and 'deepseek' in self.models:
                self.current_model_type = 'deepseek'
                self.logger.info("切换回主模型: deepseek")
            return self.models.get('deepseek', list(self.models.values())[0] if self.models else None)
    
    def create_default_models(self) -> Dict[str, Any]:
        """创建默认模型实例
        
        Returns:
            Dict[str, Any]: 创建的模型实例字典
        """
        try:
            # 加载配置
            model_config = ConfigLoader().get_config('model')
            
            # 创建主模型
            if 'deepseek' in model_config:
                deepseek_model = SentimentModelFactory.create_model('deepseek_sentiment', model_config['deepseek'])
                self.register_model('deepseek', deepseek_model)
            
            # 创建回退模型
            if self.fallback_model_type == 'bert_base':
                # 假设BERT基础模型的配置
                bert_config = {
                    'model_name': 'bert-base-chinese',
                    'max_seq_length': 512,
                    'batch_size': 16
                }
                # 这里假设SentimentModelFactory支持bert_base类型
                try:
                    bert_model = SentimentModelFactory.create_model('bert_base', bert_config)
                    self.register_model('bert_base', bert_model)
                except ValueError:
                    self.logger.warning("BERT基础模型未注册，跳过创建")
            
            return self.models
        except Exception as e:
            self.logger.error(f"创建默认模型失败: {str(e)}")
            return self.models
    
    def get_current_model_type(self) -> str:
        """获取当前使用的模型类型
        
        Returns:
            str: 当前模型类型
        """
        return self.current_model_type


# 创建全局实例
global_model_selector = ModelSelector()


def get_model_selector() -> ModelSelector:
    """获取模型选择器实例"""
    return global_model_selector